package com.wench.lock;

import java.util.concurrent.locks.ReentrantLock;

/**
 * Lock接口实现卖票
 */
public class LockSaleTicket {

    public static void main(String[] args) {

        LockTicket ticket = new LockTicket();
        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "AA").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "BB").start();

        new Thread(() -> {
            for (int i = 0; i < 40; i++) {
                ticket.sale();
            }
        }, "CC").start();
    }
}

class LockTicket {

    private int number = 30;

    private final ReentrantLock lock = new ReentrantLock();

    public void sale() {

        lock.lock();
        try {
            //  判断是否有票
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + " 卖出第 " + number-- + " 张票，剩下 " + number);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }

    }
}